package game.views;

import hx.utils.SoundManager;
import haxe.Timer;
import hx.events.Keyboard;
import hx.events.KeyboardEvent;
import hx.display.VBox;

/**
 * 可以通过上下左右控制菜单的选项功能
 */
class MenuView extends VBox {
	public var index = 0;

	override function onBuildUI() {
		super.onBuildUI();
		Timer.delay(() -> {
			focusAt(0);
		}, 16);
	}

	override function onAddToStage() {
		super.onAddToStage();
		stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
	}

	override function onRemoveToStage() {
		super.onRemoveToStage();
		stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
	}

	private function onKeyDown(e:KeyboardEvent):Void {
		switch (e.keyCode) {
			case Keyboard.W:
				index--;
				if (index < 0)
					index = children.length - 1;
				focusAt(index);
				SoundManager.getInstance().playEffect("click");
			case Keyboard.S:
				index++;
				if (index > children.length - 1)
					index = 0;
				focusAt(index);
				SoundManager.getInstance().playEffect("click");
			case Keyboard.A:
				if (currentSelectedConfigSetItem != null) {
					currentSelectedConfigSetItem.onPrev();
					SoundManager.getInstance().playEffect("click");
				}
			case Keyboard.D:
				if (currentSelectedConfigSetItem != null) {
					currentSelectedConfigSetItem.onNext();
					SoundManager.getInstance().playEffect("click");
				}
			case Keyboard.J:
				if (currentSelectedConfigSetItem != null) {
					currentSelectedConfigSetItem.onOk();
					SoundManager.getInstance().playEffect("selected");
				}
		}
	}

	public var currentSelectedConfigSetItem:IMenuItem;

	public function focusAt(index:Int):Void {
		this.index = index;
		for (i => object in this.children) {
			if (object is IMenuItem) {
				var config:IMenuItem = cast object;
				config.setSelected(index == i);
				if (index == i) {
					currentSelectedConfigSetItem = config;
				}
			}
		}
	}
}
